package cn.sunxinao.pm.json;

import cn.sunxinao.pm.models.AbstractPet;
import cn.sunxinao.pm.models.AbstractUser;
import cn.sunxinao.pm.utils.IReadWriteTool;
import com.google.gson.FieldNamingPolicy;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

public class ReadWriteTool implements IReadWriteTool {
    private static final Gson gson = new GsonBuilder()
        .setPrettyPrinting()
        .setFieldNamingStrategy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES)
        .create();

    @Override
    public List<AbstractPet> readAllPets(File file) {
        if (!file.exists() || file.length() == 0) saveAllPets(new ArrayList<>(), file);
        try (FileReader fileReader = new FileReader(file)) {
            Type collectionType = new TypeToken<List<Pet>>() {
            }.getType();
            return gson.fromJson(fileReader, collectionType);
        } catch (IOException e) {
            e.printStackTrace();
            System.err.println("提示: 无法访问文件，数据可能无法保存");
            return null;
        }
    }

    @Override
    public boolean saveAllPets(List<AbstractPet> pets, File file) {
        try (FileWriter fileWriter = new FileWriter(file, false)) {
            fileWriter.write(gson.toJson(pets));
            fileWriter.flush();
            return true;
        } catch (IOException e) {
            e.printStackTrace();
            System.err.println("提示: 无法访问文件，数据可能无法保存");
            return false;
        }
    }

    @Override
    public List<AbstractUser> readAllUsers(File file) {
        if (!file.exists() || file.length() == 0) saveAllUsers(new ArrayList<>(), file);
        try (FileReader fileReader = new FileReader(file)) {
            Type collectionType = new TypeToken<List<User>>() {
            }.getType();
            return gson.fromJson(fileReader, collectionType);
        } catch (IOException e) {
            e.printStackTrace();
            System.err.println("提示: 无法访问文件，数据可能无法保存");
            return null;
        }
    }

    @Override
    public boolean saveAllUsers(List<AbstractUser> users, File file) {
        try (FileWriter fileWriter = new FileWriter(file, false)) {
            fileWriter.write(gson.toJson(users));
            fileWriter.flush();
            return true;
        } catch (IOException e) {
            e.printStackTrace();
            System.err.println("提示: 无法访问文件，数据可能无法保存");
            return false;
        }
    }
}
